<template>
  <div class="system-monitor-container">
    <!-- 页面标题区域 -->
    <div class="page-header-wrapper">
      <div class="page-title-section">
        <h1 class="page-title">系统监控</h1>
        <p class="page-description">实时监控系统资源使用情况、业务指标和租户隔离状态</p>
      </div>
      <div class="page-actions-section">
        <button
          @click="refreshData"
          :disabled="loading"
          class="primary-action-btn bg-primary hover:bg-primary-hover text-white px-4 py-2 rounded-md flex items-center shadow-card transition-all"
        >
          <i class="fas fa-sync mr-2" :class="{ 'animate-spin': loading }"></i>
          <span>刷新数据</span>
        </button>
        <button
          @click="toggleAutoRefresh"
          :class="autoRefresh ? 'bg-success hover:bg-success-hover' : 'bg-secondary hover:bg-secondary-hover'"
          class="text-white px-4 py-2 rounded-md flex items-center shadow-card transition-all"
        >
          <i class="fas fa-play mr-2" v-if="!autoRefresh"></i>
          <i class="fas fa-pause mr-2" v-else></i>
          <span>{{ autoRefresh ? '停止自动刷新' : '自动刷新' }}</span>
        </button>
      </div>
    </div>

    <!-- 系统资源统计卡片 -->
    <div class="metrics-grid-section">
      <h2 class="section-title">系统资源概览</h2>
      <div class="metrics-grid">
      <div class="metric-card bg-panel rounded-lg shadow-card p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-text-muted text-sm">CPU使用率</p>
            <p class="text-2xl font-bold text-text-primary">{{ formatPercent(systemInfo?.cpuUsage) }}</p>
            <p class="text-text-secondary text-sm">{{ systemInfo?.cpuCores }} 核心</p>
          </div>
          <div class="metric-icon bg-blue-500/20 text-blue-600 rounded-full p-3">
            <i class="fas fa-microchip text-xl"></i>
          </div>
        </div>
        <div class="mt-3">
          <div class="progress-bar bg-bg-hover rounded-full h-2">
            <div 
              class="progress-fill bg-blue-500 rounded-full h-2 transition-all duration-300"
              :style="{ width: `${Math.min(systemInfo?.cpuUsage || 0, 100)}%` }"
            ></div>
          </div>
        </div>
      </div>

      <div class="metric-card bg-panel rounded-lg shadow-card p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-text-muted text-sm">内存使用率</p>
            <p class="text-2xl font-bold text-text-primary">{{ formatPercent(systemInfo?.memoryUsage) }}</p>
            <p class="text-text-secondary text-sm">{{ formatBytes(systemInfo?.usedMemory) }} / {{ formatBytes(systemInfo?.totalMemory) }}</p>
          </div>
          <div class="metric-icon bg-green-500/20 text-green-600 rounded-full p-3">
            <i class="fas fa-memory text-xl"></i>
          </div>
        </div>
        <div class="mt-3">
          <div class="progress-bar bg-bg-hover rounded-full h-2">
            <div 
              class="progress-fill bg-green-500 rounded-full h-2 transition-all duration-300"
              :style="{ width: `${Math.min(systemInfo?.memoryUsage || 0, 100)}%` }"
            ></div>
          </div>
        </div>
      </div>

      <div class="metric-card bg-panel rounded-lg shadow-card p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-text-muted text-sm">在线用户</p>
            <p class="text-2xl font-bold text-text-primary">{{ businessStats?.onlineUsers || 0 }}</p>
            <p class="text-text-secondary text-sm">活跃: {{ businessStats?.activeUsers || 0 }}</p>
          </div>
          <div class="metric-icon bg-purple-500/20 text-purple-600 rounded-full p-3">
            <i class="fas fa-users text-xl"></i>
          </div>
        </div>
      </div>

      <div class="metric-card bg-panel rounded-lg shadow-card p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-text-muted text-sm">缓存合规率</p>
            <p class="text-2xl font-bold text-text-primary">{{ formatPercent(tenantMetrics?.formatCompliance?.overallCompliance) }}</p>
            <p class="text-text-secondary text-sm">总键: {{ cacheValidationReport?.totalKeys || 0 }}</p>
          </div>
          <div class="metric-icon bg-orange-500/20 text-orange-600 rounded-full p-3">
            <i class="fas fa-database text-xl"></i>
          </div>
        </div>
        <div class="mt-3">
          <div class="progress-bar bg-bg-hover rounded-full h-2">
            <div 
              class="progress-fill bg-orange-500 rounded-full h-2 transition-all duration-300"
              :style="{ width: `${Math.min(tenantMetrics?.formatCompliance?.overallCompliance || 0, 100)}%` }"
            ></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 详细监控数据 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
      <!-- 系统资源监控 -->
      <div class="monitor-panel bg-panel rounded-lg shadow-card p-6">
        <div class="panel-header flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-text-primary">系统资源</h3>
          <div class="status-indicator flex items-center text-sm">
            <div class="w-2 h-2 rounded-full bg-green-500 mr-2"></div>
            <span class="text-text-secondary">运行正常</span>
          </div>
        </div>

        <div class="space-y-4">
          <!-- JVM内存 -->
          <div class="metric-item">
            <div class="flex justify-between items-center mb-2">
              <span class="text-text-secondary">JVM堆内存</span>
              <span class="text-text-primary font-medium">{{ formatPercent(systemInfo?.jvmMemoryUsage?.usage) }}</span>
            </div>
            <div class="progress-bar bg-bg-hover rounded-full h-2">
              <div 
                class="progress-fill bg-yellow-500 rounded-full h-2 transition-all duration-300"
                :style="{ width: `${Math.min(systemInfo?.jvmMemoryUsage?.usage || 0, 100)}%` }"
              ></div>
            </div>
            <div class="text-xs text-text-muted mt-1">
              {{ formatBytes(systemInfo?.jvmMemoryUsage?.used) }} / {{ formatBytes(systemInfo?.jvmMemoryUsage?.max) }}
            </div>
          </div>

          <!-- 磁盘使用 -->
          <div class="metric-item" v-for="disk in systemInfo?.diskInfos" :key="disk.path">
            <div class="flex justify-between items-center mb-2">
              <span class="text-text-secondary">磁盘 {{ disk.path }}</span>
              <span class="text-text-primary font-medium">{{ formatPercent(disk.usage) }}</span>
            </div>
            <div class="progress-bar bg-bg-hover rounded-full h-2">
              <div 
                class="progress-fill bg-red-500 rounded-full h-2 transition-all duration-300"
                :style="{ width: `${Math.min(disk.usage, 100)}%` }"
              ></div>
            </div>
            <div class="text-xs text-text-muted mt-1">
              {{ formatBytes(disk.used) }} / {{ formatBytes(disk.total) }}
            </div>
          </div>

          <!-- 系统信息 -->
          <div class="system-info mt-4 pt-4 border-t border-border">
            <div class="text-sm text-text-secondary space-y-1">
              <div>JVM版本: {{ systemInfo?.jvmVersion }}</div>
              <div>运行时间: {{ formatUptime(systemInfo?.jvmUptime) }}</div>
              <div>更新时间: {{ formatTime(systemInfo?.timestamp) }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 业务统计监控 -->
      <div class="monitor-panel bg-panel rounded-lg shadow-card p-6">
        <div class="panel-header flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-text-primary">业务统计</h3>
        </div>

        <div class="space-y-4">
          <!-- 用户统计 -->
          <div class="stat-section">
            <h4 class="text-text-secondary text-sm mb-3">用户统计</h4>
            <div class="grid grid-cols-3 gap-4">
              <div class="text-center">
                <div class="text-xl font-bold text-text-primary">{{ businessStats?.totalUsers || 0 }}</div>
                <div class="text-xs text-text-muted">总用户数</div>
              </div>
              <div class="text-center">
                <div class="text-xl font-bold text-green-600">{{ businessStats?.activeUsers || 0 }}</div>
                <div class="text-xs text-text-muted">活跃用户</div>
              </div>
              <div class="text-center">
                <div class="text-xl font-bold text-blue-600">{{ businessStats?.onlineUsers || 0 }}</div>
                <div class="text-xs text-text-muted">在线用户</div>
              </div>
            </div>
          </div>

          <!-- 租户统计 -->
          <div class="stat-section" v-if="businessStats?.tenantStats">
            <h4 class="text-text-secondary text-sm mb-3">租户统计</h4>
            <div class="grid grid-cols-2 gap-4">
              <div class="text-center">
                <div class="text-xl font-bold text-text-primary">{{ businessStats.tenantStats.totalTenants || 0 }}</div>
                <div class="text-xs text-text-muted">总租户数</div>
              </div>
              <div class="text-center">
                <div class="text-xl font-bold text-green-600">{{ businessStats.tenantStats.activeTenants || 0 }}</div>
                <div class="text-xs text-text-muted">活跃租户</div>
              </div>
            </div>
          </div>

          <!-- 权限使用统计 -->
          <div class="stat-section" v-if="businessStats?.permissionUsageStats">
            <h4 class="text-text-secondary text-sm mb-3">热门权限</h4>
            <div class="space-y-2">
              <div 
                v-for="[permission, count] in Object.entries(businessStats.permissionUsageStats).slice(0, 5)" 
                :key="permission"
                class="flex justify-between items-center text-sm"
              >
                <span class="text-text-secondary truncate">{{ permission }}</span>
                <span class="text-text-primary font-medium">{{ count }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    </div>
    
    <!-- 租户隔离监控 -->
    <div class="tenant-monitoring-section" v-if="tenantMetrics">
      <div class="monitor-panel"
      <div class="panel-header flex items-center justify-between mb-4">
        <h3 class="text-lg font-semibold text-text-primary">租户隔离监控</h3>
        <div class="status-indicator flex items-center text-sm">
          <div 
            class="w-2 h-2 rounded-full mr-2"
            :class="tenantMetrics.crossTenantLeakageWarnings.length === 0 ? 'bg-green-500' : 'bg-red-500'"
          ></div>
          <span class="text-text-secondary">
            {{ tenantMetrics.crossTenantLeakageWarnings.length === 0 ? '隔离正常' : '存在异常' }}
          </span>
        </div>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <!-- 租户缓存分布 -->
        <div class="tenant-section">
          <h4 class="text-text-secondary text-sm mb-3">租户缓存分布</h4>
          <div class="space-y-2">
            <div 
              v-for="[tenantId, count] in Object.entries(tenantMetrics.tenantCacheKeyCount)"
              :key="tenantId"
              class="flex justify-between items-center text-sm"
            >
              <span class="text-text-secondary">{{ tenantId }}</span>
              <span class="text-text-primary font-medium">{{ count }} 键</span>
            </div>
          </div>
        </div>

        <!-- 缓存命中率 -->
        <div class="tenant-section">
          <h4 class="text-text-secondary text-sm mb-3">缓存命中率</h4>
          <div class="space-y-2">
            <div 
              v-for="[tenantId, hitRate] in Object.entries(tenantMetrics.tenantCacheHitRate)"
              :key="tenantId"
              class="flex justify-between items-center text-sm"
            >
              <span class="text-text-secondary">{{ tenantId }}</span>
              <span class="text-text-primary font-medium">{{ formatPercent(hitRate) }}</span>
            </div>
          </div>
        </div>

        <!-- 格式合规性 -->
        <div class="tenant-section">
          <h4 class="text-text-secondary text-sm mb-3">格式问题</h4>
          <div class="space-y-2">
            <div 
              v-for="issue in tenantMetrics.formatCompliance.commonIssues"
              :key="issue"
              class="text-sm text-red-600"
            >
              {{ issue }}
            </div>
            <div v-if="tenantMetrics.formatCompliance.commonIssues.length === 0" class="text-sm text-green-600">
              无格式问题
            </div>
          </div>
        </div>
      </div>

      <!-- 跨租户泄露警告 -->
      <div v-if="tenantMetrics.crossTenantLeakageWarnings.length > 0" class="mt-6 p-4 bg-red-50 border border-red-200 rounded-lg">
        <h4 class="text-red-800 font-medium mb-2">🚨 跨租户泄露警告</h4>
        <ul class="text-sm text-red-700 space-y-1">
          <li v-for="warning in tenantMetrics.crossTenantLeakageWarnings" :key="warning">
            • {{ warning }}
          </li>
        </ul>
      </div>
    </div>

    <!-- 缓存键验证报告 -->
    <div class="monitor-panel bg-panel rounded-lg shadow-card p-6" v-if="cacheValidationReport">
      <div class="panel-header flex items-center justify-between mb-4">
        <h3 class="text-lg font-semibold text-text-primary">缓存键验证报告</h3>
        <div class="status-indicator flex items-center text-sm">
          <div 
            class="w-2 h-2 rounded-full mr-2"
            :class="cacheValidationReport.complianceRate >= 95 ? 'bg-green-500' : 'bg-yellow-500'"
          ></div>
          <span class="text-text-secondary">
            合规率 {{ formatPercent(cacheValidationReport.complianceRate) }}
          </span>
        </div>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
        <div class="stat-item text-center">
          <div class="text-2xl font-bold text-text-primary">{{ cacheValidationReport.totalKeys }}</div>
          <div class="text-text-muted text-sm">总键数</div>
        </div>
        <div class="stat-item text-center">
          <div class="text-2xl font-bold text-green-600">{{ cacheValidationReport.validKeys }}</div>
          <div class="text-text-muted text-sm">有效键</div>
        </div>
        <div class="stat-item text-center">
          <div class="text-2xl font-bold text-red-600">{{ cacheValidationReport.invalidKeys }}</div>
          <div class="text-text-muted text-sm">无效键</div>
        </div>
        <div class="stat-item text-center">
          <div class="text-2xl font-bold text-blue-600">{{ formatPercent(cacheValidationReport.complianceRate) }}</div>
          <div class="text-text-muted text-sm">合规率</div>
        </div>
      </div>

      <!-- 无效键示例 -->
      <div v-if="cacheValidationReport.invalidKeyExamples.length > 0" class="mb-4">
        <h4 class="text-text-secondary text-sm mb-3">无效键示例</h4>
        <div class="bg-red-50 border border-red-200 rounded-lg p-3">
          <ul class="text-sm text-red-700 space-y-1">
            <li v-for="example in cacheValidationReport.invalidKeyExamples" :key="example">
              <code class="bg-red-100 px-1 rounded">{{ example }}</code>
            </li>
          </ul>
        </div>
      </div>

      <!-- 优化建议 -->
      <div v-if="cacheValidationReport.recommendations.length > 0">
        <h4 class="text-text-secondary text-sm mb-3">优化建议</h4>
        <div class="bg-blue-50 border border-blue-200 rounded-lg p-3">
          <ul class="text-sm text-blue-700 space-y-1">
            <li v-for="recommendation in cacheValidationReport.recommendations" :key="recommendation">
              • {{ recommendation }}
            </li>
          </ul>
        </div>
      </div>
    </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { systemMonitorApi, userStatisticsApi } from '@/api/monitor'
import type { SystemInfo, TenantIsolationMetrics, CacheKeyValidationReport } from '@/api/monitor'
// BusinessStatistics 类型已迁移至 userStatisticsApi

// 响应式数据
const loading = ref(false)
const autoRefresh = ref(false)
const refreshInterval = ref<NodeJS.Timeout>()

const systemInfo = ref<SystemInfo>()
const businessStats = ref<BusinessStatistics>()
const tenantMetrics = ref<TenantIsolationMetrics>()
const cacheValidationReport = ref<CacheKeyValidationReport>()

// 获取系统监控数据
const loadSystemInfo = async () => {
  try {
    const response = await systemMonitorApi.getSystemInfo()
    systemInfo.value = response.data
  } catch (error) {
    console.error('获取系统信息失败:', error)
  }
}

// ✅ 获取业务统计数据（已迁移至用户统计API）
const loadBusinessStats = async () => {
  try {
    const response = await userStatisticsApi.getBusinessStatistics()
    businessStats.value = response.data
  } catch (error) {
    console.error('获取业务统计失败:', error)
  }
}

// 获取租户隔离监控数据
const loadTenantMetrics = async () => {
  try {
    const response = await systemMonitorApi.getTenantIsolationMetrics()
    tenantMetrics.value = response.data
  } catch (error) {
    console.error('获取租户监控数据失败:', error)
  }
}

// 获取缓存键验证报告
const loadCacheValidationReport = async () => {
  try {
    const response = await systemMonitorApi.getCacheKeyValidationReport()
    cacheValidationReport.value = response.data
  } catch (error) {
    console.error('获取缓存键验证报告失败:', error)
  }
}

// 刷新所有数据
const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([
      loadSystemInfo(),
      loadBusinessStats(),
      loadTenantMetrics(),
      loadCacheValidationReport()
    ])
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  } finally {
    loading.value = false
  }
}

// 切换自动刷新
const toggleAutoRefresh = () => {
  autoRefresh.value = !autoRefresh.value
  
  if (autoRefresh.value) {
    refreshInterval.value = setInterval(refreshData, 30000) // 30秒刷新一次
    ElMessage.success('已开启自动刷新 (30秒)')
  } else {
    if (refreshInterval.value) {
      clearInterval(refreshInterval.value)
      refreshInterval.value = undefined
    }
    ElMessage.info('已停止自动刷新')
  }
}

// 格式化工具函数
const formatPercent = (value?: number): string => {
  if (typeof value !== 'number') return '0%'
  return `${Math.round(value)}%`
}

const formatBytes = (bytes?: number): string => {
  if (typeof bytes !== 'number') return '0 B'
  
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let size = bytes
  let unitIndex = 0
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }
  
  return `${size.toFixed(1)} ${units[unitIndex]}`
}

const formatUptime = (uptime?: number): string => {
  if (typeof uptime !== 'number') return '0秒'
  
  const seconds = Math.floor(uptime / 1000)
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (days > 0) return `${days}天 ${hours}小时`
  if (hours > 0) return `${hours}小时 ${minutes}分钟`
  return `${minutes}分钟`
}

const formatTime = (timestamp?: string): string => {
  if (!timestamp) return ''
  return new Date(timestamp).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  refreshData()
})

onUnmounted(() => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value)
  }
})
</script>

<style scoped>
.metric-card {
  transition: all 0.3s ease;
}

.metric-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.metric-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.progress-bar {
  overflow: hidden;
}

.progress-fill {
  transition: width 0.6s ease-in-out;
}

.monitor-panel {
  transition: all 0.3s ease;
}

.monitor-panel:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
}

.status-indicator {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}
</style>
